package com.jolink.omiis.wechat.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jolink.omiis.wechat.keys.IPreferences;

/**
 * 
 * 腾讯签名合法性校验
 * 
 * @author WangYanqing
 *
 */
@Deprecated
public class SignatureUtil {
	private static Logger logger = LoggerFactory.getLogger(SignatureUtil.class);

	private SignatureUtil() {

	}

	public static String validSignature(Map<String, String[]> params) {
		String signature = params.get("signature")[0];
		String timestamp = params.get("timestamp")[0];
		String nonce = params.get("nonce")[0];
		String echostr = params.get("echostr")[0];
		logger.info("接收到来自腾讯服务器的合法性认证，signature=" + signature + ",timestamp=" + timestamp + ",nonce=" + nonce
				+ ",echostr=" + echostr);
		String[] array = new String[] { IPreferences.TOKEN, timestamp, nonce };
		Arrays.sort(array);
		StringBuffer sb = new StringBuffer();
		for (String temp : array) {
			sb.append(temp);
		}
		logger.info("字典排序后拼接字符串：" + sb.toString());
		String sha1_key = SHA1(sb.toString());
		logger.info("进行SHA-1加密后：" + sha1_key);
		if (sha1_key.equals(signature)) {
			logger.info("验证成功");
			return echostr;
		} else {
			return "fail";
		}
	}

	private static String SHA1(String descript) {
		logger.info("SHA1加密认证：{}", descript);
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
			digest.update(descript.getBytes());
			byte messageDigest[] = digest.digest();
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			logger.error(e.getMessage(), e);
		}
		return "unknown";
	}
}
